#!/usr/bin/python
import sqlite3
import sys

class Sqlite_db():
	"""Database sqlite3 class"""
	def __init__(self, name):
		try:
			self.__name = name
			self.__last_query = None
			self.__commit = True
			self.__conn = None
			self.__cursor = None
		except Exception,e:
			print "Error while setting up database connection - %s" %e
			sys.exit(1)
	def connection(self):
		self.__conn = sqlite3.connect(self.__name)
	   	self.__cursor = self.__conn.cursor()
		return self.__conn,self.__cursor
		#print sqlite3.__file__,sqlite3.version

	def getcursor(self):
		if self__cursor:
			return self.__cursor
		else:
			return None

	def getconnection(self):
		if self.__conn:
			return self.__conn
		else:
			return None

	def getlastquery(self):
		return self.__last_query

	def disconnection(self):
		if self.__conn:
			self.__cursor.close()
			self.__conn.close()


	def commit(self,commit_flag=True):
		if commit_flag:
			self.__commit = True
		else:
			self.__commit = False

	def getrow(self,query,bind_var):
		self.__last_query = None
		try:   
			self.__cursor.execute(query,bind_var)
			r = self.__cursor.fetchall()
			self.__last_query = "%s %s" % (query, bind_var) # display it on error
			return r
		except Exception, e:
			print "Error while executing query %s %s:%s" % (query,bind_var,e)

	def getrows(self,query,bind_var,nkeys=1):
		self.__result = {}
		self.__last_query = None
		try:
			self.__cursor.execute(query,bind_var)
			self.__last_query = "%s %s" % (query, bind_var)
			row = self.__cursor.fetchone()
			while row:
				key = row[:nkeys]
				val = row[nkeys:]
				key = len(key) == 1 and key[0] or key
		                val = len(val) == 1 and val[0] or val
		                self.__result[key] = val
		                row = self.__cursor.fetchone()
		except Exception,e:
			print "Error while executing query %s %s:%s" % (query,bind_var,e)
		return self.__result	

	def execute_query(self,query,bind_var):
		self.__last_query = None
		try:
			r = self.__cursor.execute(query,bind_var)
			if self.__commit:
				self.__conn.commit()
			self.__last_query = "%s %s" % (query, bind_var)
			return r
		except Exception,e:
			print "Error while executing query %s %s:%s" % (query,bind_var,e)

